<template>
  <div
    v-loading="loading"
    class="add-box"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 1)"
  >
    <el-input
      v-if="!isEdit || defaultChecked.length"
      v-model="filterText"
      class="tree-select-input"
      size="medium"
      placeholder="输入关键字搜索"
    />
    <div class="tree-box">
      <div v-if="!isEdit" class="header-box mb-10">
        <el-checkbox
          v-model="isSelectAll"
          class="mt-10"
          @change="selectAll('tree', 'deptTree')"
        >全选/全不选</el-checkbox>
        <el-checkbox
          v-model="isExpand"
          @change="expandAll('tree', 'deptTree')"
        >展开/折叠</el-checkbox>
      </div>
      <el-tree
        ref="tree"
        class="filter-tree"
        :data="deptTree"
        :default-checked-keys="defaultChecked"
        default-expand-all
        show-checkbox
        empty-text="暂无所属用户"
        node-key="id"
        accordion
        :props="defaultProps"
        :filter-node-method="filterNode"
      >
        <span
          slot-scope="{ node, data }"
          class="custom-tree-node flex flex-aic"
        >
          <span class="flex flex-aic">
            <!-- 人图标 -->
            <img
              v-if="data.type === '1' && data.avatarUrl"
              width="16px"
              height="16px"
              style="margin-right: 8px; border-radius: 50%"
              :src="data.avatarUrl"
              alt=""
            >
            <!-- 部门图标 -->
            <img
              v-else-if="data.type === '2'"
              width="16px"
              height="16px"
              style="margin-right: 8px"
              src="@/assets/images/level1.png"
              alt=""
            >
            <!-- icon -->
            <i v-else-if="data.type === '1' && !data.avatarUrl" style="margin-right: 8px" class="el-icon-user" />
          </span>
          <!-- 人名称+昵称 -->
          <span v-if="data.fullName"> {{ data.fullName }} </span>
          <span v-if="data.fullName"> ( {{ node.label }} ) </span>
          <!-- 部门名称 -->
          <span v-if="!data.fullName" :style="{ 'font-weight': 'bold' }">
            {{ node.label }}
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'
import { elementMixin } from '@/mixin/element'
export default {
  name: 'RoleManageUser',
  mixins: [elementMixin],
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      menuTree: [],
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'userName'
      },
      defaultChecked: [],
      defaultOpen: [],
      deptList: [],
      userList: [],
      deptTree: [],
      isEdit: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    confirm() {
      this.submit()
    }
  },
  created() {
    this.isEdit = this.popConfig.popType !== 'edit'
    this.queryAscriptionUser()
    this.getDeptTree()
  },
  methods: {
    // 组织架构
    async getDeptTree() {
      this.loading = true
      const params = {}
      try {
        const res = await this.$api.deptTree(params)
        if (res.code === '1000') {
          this.deptList = res.data
          this.deptList.forEach((e) => {
            e.id = 'dept-' + e.id
            e.parentId = 'dept-' + e.parentId
            e.userName = e.deptName
            e.type = '2'
            e.disabled = this.isEdit
          })
          this.getUserList()
        } else {
          console.log('数据异常')
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 所有用户
    async getUserList() {
      const params = {}
      try {
        const res = await this.$api.queryUserList(params)
        if (res.code === '1000') {
          this.userList = res.data
          this.userList.forEach((e) => {
            e.parentId = 'dept-' + e.deptId
            e.disabled = this.isEdit
            e.type = '1'
          })
          const arr = [...this.deptList, ...this.userList]
          this.deptTree = await arr2tree(arr, {
            id: 'id',
            parentId: 'parentId',
            childrenKey: 'children'
          })
          this.$nextTick(() => {
            this.$refs.tree.filter()
          })
        } else {
          console.log('数据异常')
        }
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    // 获取当前角色下的用户
    async queryAscriptionUser() {
      const params = { id: this.popData.id }
      try {
        const res = await this.$api.roleManage.queryAscriptionUser(params)
        if (res.code === '1000') {
          const userList = res.data || []
          this.setCheckedKeys(userList)
        } else {
          console.log('数据异常')
        }
      } catch (error) {
        console.log(error)
      }
    },

    async submit() {
      const ids = this.$refs.tree
        .getCheckedKeys()
        .filter((e) => e.indexOf('dept'))
      const params = {
        roleId: this.popData.id,
        userIdList: ids
      }
      this.loading = true
      try {
        const res = await this.$api.roleManage.updateAscriptionUser(params)
        if (res.code === '1000') {
          this.$message.success('设置成功！')
          this.$emit('onFinish', 'role-user')
        }
      } catch (error) {
        console.log('error')
      }
      this.loading = false
    },
    filterNode(value, data, node) {
      // 查看状态
      if (this.isEdit) {
        if (!value) return node.checked || node.indeterminate
        return (
          data.userName.indexOf(value) !== -1 &&
          (node.checked || node.indeterminate)
        )
      } else {
        // 编辑状态
        if (!value) return true
        return data.userName.indexOf(value) !== -1
      }
    },
    // 设置默认勾选的节点
    setCheckedKeys(list) {
      list.forEach((e) => {
        this.defaultChecked.push(e.id)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-box {
  color: #333;
  height: 50vh;
  display: flex;
  flex-direction: column;
  padding: 0 20px;

  .tree-box {
    flex: 1;
    overflow-y: auto;
    .filter-tree {
      height: 100%;
    }
  }

  .tree-select-input {
    width: 50%;
    margin-bottom: 15px;
  }

  .custom-tree-node {
    display: flex;
    align-items: center;
  }

  ::v-deep .el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner,
  ::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: rgb(219,139,57);
    border-color: rgb(219,139,57);
  }
}
</style>
